<template>
	<view class="address-edit-container">
		<!-- 表单内容 -->
		<view class="form-item">
			<text class="label">楼栋</text>
			<text class="readonly-value">{{ building }}</text>
		</view>
		<view class="form-item">
			<text class="label">详细地址</text>
			<input class="input" type="text" placeholder="输入门牌号" v-model="detailAddress" />
		</view>
		<view class="form-item">
			<text class="label">姓名</text>
			<input class="input" type="text" placeholder="输入姓名" v-model="name" />
		</view>
		<view class="form-item">
			<text class="label">联系电话</text>
			<input class="input" type="number" placeholder="输入联系电话" v-model="phone" @blur="validatePhone" />
			<text class="error-tip" v-if="phoneError">{{ phoneError }}</text>
		</view>
		<!-- 保存按钮 -->
		<button class="save-btn" @click="onSave">保存地址</button>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		addAddressSuShe
	} from '@/package/api/insertList.js';

	// 从本地存储获取楼栋信息
	const building = ref('');
	const detailAddress = ref('');
	const name = ref('');
	const phone = ref('');
	const phoneError = ref(''); // 手机号错误提示
	const loading = ref(false); // 加载状态

	// 从本地存储获取学校和楼栋信息
	const schoolId = ref('');
	const schoolName = ref('');
	const buildingId = ref('');
	const buildingName = ref('');

	onMounted(() => {
		// 从本地存储获取楼栋信息
		try {
			const selectedBuildingText = uni.getStorageSync('selectedBuildingText');
			const selectedBuildingId = uni.getStorageSync('selectedBuilding');

			if (selectedBuildingText) {
				building.value = selectedBuildingText;
				buildingName.value = selectedBuildingText;
			} else {
				building.value = '未选择楼栋';
				buildingName.value = '未选择楼栋';
			}

			if (selectedBuildingId) {
				buildingId.value = selectedBuildingId;
			} else {
				buildingId.value = '';
			}

			// 获取学校信息
			const storedSchoolName = uni.getStorageSync("school_name");
			const storedSchoolId = uni.getStorageSync('school_id');

			if (storedSchoolName) {
				schoolName.value = storedSchoolName;
			} else {
				schoolName.value = '';
			}

			if (storedSchoolId) {
				schoolId.value = storedSchoolId;
			} else {
				schoolId.value = '';
			}
		} catch (e) {
			console.error('获取本地存储失败:', e);
			building.value = '获取楼栋信息失败';
			buildingName.value = '获取楼栋信息失败';
			schoolName.value = '';
			schoolId.value = '';
		}
	});

	// 关闭页面回调
	const onClose = () => {
		uni.navigateBack();
	};

	// 显示加载提示
	const showLoading = (title = '加载中') => {
		loading.value = true;
		uni.showLoading({
			title,
			mask: true
		});
	};

	// 隐藏加载提示
	const hideLoading = () => {
		loading.value = false;
		uni.hideLoading();
	};

	// 显示提示框
	const showToast = (title, icon = 'none', duration = 2000) => {
		uni.showToast({
			title,
			icon,
			duration
		});
	};

	// 手机号验证（失焦时触发）
	const validatePhone = () => {
		if (phone.value) {
			const isValid = validateChinaPhone(phone.value + '');
			if (!isValid) {
				phoneError.value = '请输入正确的手机号码';
			} else {
				phoneError.value = '';
			}
		}
	};

	// 严谨的中国大陆手机号正则（覆盖所有号段）
	const validateChinaPhone = (phone) => {
		const reg = /^1[3-9]\d{9}$/;
		return reg.test(phone);
	};

	// 保存地址逻辑
	const onSave = async () => {
		// 表单验证
		if (!detailAddress.value || !name.value || !phone.value) {
			showToast('请填写完整信息');
			return;
		}

		// 手机号验证
		if (!validateChinaPhone(phone.value + '')) {
			showToast('请输入正确的手机号码');
			return;
		}

		// 显示加载中
		showLoading('保存中...');

		try {
			// 封装请求参数
			const addressData = {
				buildingId: buildingId.value,
				buildingName: buildingName.value,
				schoolId: schoolId.value,
				schoolName: schoolName.value,
				realName: name.value,
				phone: phone.value + '',
				detailAddress: detailAddress.value
			};

			// 调用后台接口
			const response = await addAddressSuShe(addressData);

			// 隐藏加载
			hideLoading();

			if (response.code === 200) {
				showToast('保存成功', 'success');

				// 新增：存储地址信息和返回的ID到本地存储
				const addressId = response.data; // 假设接口返回的ID在data字段
				const addressInfo = {
					id: addressId,
					buildingId: buildingId.value,
					buildingName: buildingName.value,
					schoolId: schoolId.value,
					schoolName: schoolName.value,
					realName: name.value,
					phone: phone.value,
					detailAddress: detailAddress.value,
					createTime: new Date().toISOString() // 添加创建时间
				};

				// 存储到本地存储
				try {
					// 获取已有的地址列表，没有则创建空数组
					let addressList = uni.getStorageSync('userAddressList') || [];
					// 添加新地址
					addressList.push(addressInfo);
					// 存储更新后的地址列表
					uni.setStorageSync('userAddressList', addressList);
					// 单独存储最新地址ID
					uni.setStorageSync('latestAddressId', addressId);
					console.log('地址信息已存储到本地存储:', addressInfo);
				} catch (storageError) {
					console.error('本地存储失败:', storageError);
					showToast('本地存储失败，请稍后重试');
				}

				// 保存成功后返回上一页
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} else {
				showToast(response.message || '保存失败，请重试');
			}
		} catch (error) {
			// 隐藏加载
			hideLoading();
			console.error('保存地址失败', error);
			showToast('保存失败，请重试');
		}
	};
</script>

<style scoped>
	/* 样式保持不变 */
	.address-edit-container {
		padding: 20rpx;
		background-color: #fff;
		border-radius: 16rpx;
		margin: 20rpx;
		position: relative;
	}

	.close-btn {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
	}

	.close-icon {
		font-size: 36rpx;
		color: #999;
	}

	.form-item {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		margin-bottom: 30rpx;
	}

	.label {
		width: 100%;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}

	.readonly-value {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 28rpx;
		color: #666;
		padding-left: 4rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
	}

	.input {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 28rpx;
		color: #333;
		border-bottom: 1px solid #eee;
	}

	/* 错误提示样式 */
	.error-tip {
		font-size: 24rpx;
		color: #ff5a5f;
		margin-top: 4rpx;
	}

	.save-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #ff7d00;
		color: #fff;
		font-size: 32rpx;
		border-radius: 40rpx;
	}
</style>